package com.china08.yxyapi.service.yxyresource.statistics.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import com.china08.yxyapi.entity.db.res.YxyResPhase;
import com.china08.yxyapi.repository.db.YxyResPhaseRepository;
import com.china08.yxyapi.repository.mg.lecture.YxyLecturePrePackRepository;
import com.china08.yxyapi.service.yxyresource.statistics.ResourceSubNameCountService;

/**
 * 资源统计 各学段资源
 * 
 * @author yyy
 *
 */
@Service
public class ResourceSubNameCountServiceImpl implements ResourceSubNameCountService {
    @Autowired
    private ElasticsearchTemplate et;
    @Autowired
    private YxyResPhaseRepository yxyResPhaseRepository;

    @Override
    public Map<String, Object> statisticsResourceTypeCount(String districtCode, Integer schoolBureauLevel) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderType = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderType);
        if (schoolBureauLevel == 0) {
            TermQueryBuilder builderDel = new TermQueryBuilder("districtCode", districtCode);
            boolQueryBuilder.must(builderDel);
        } else if (schoolBureauLevel == 1) {
            TermQueryBuilder builderDel = new TermQueryBuilder("cityCode", districtCode);
            boolQueryBuilder.must(builderDel);
        } else if (schoolBureauLevel == 2) {
            TermQueryBuilder builderDel = new TermQueryBuilder("provinceCode", districtCode);
            boolQueryBuilder.must(builderDel);
        }

        boolQueryBuilder.mustNot(builderType2);
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("subjectIdList").size(100);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);

            System.out.println(key + "科目有" + value + "个资源。");
            System.out.println();
        }
        return map;
    }

    @Override
    public Map<String, Object> statisticsWeikePhaseCount(String xueduan, String districtCode, Integer schoolBureauLevel) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderTypee = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderTypee);
        if (schoolBureauLevel == 0) {
            TermQueryBuilder builderDel = new TermQueryBuilder("districtCode", districtCode);
            boolQueryBuilder.must(builderDel);
        } else if (schoolBureauLevel == 1) {
            TermQueryBuilder builderDel = new TermQueryBuilder("cityCode", districtCode);
            boolQueryBuilder.must(builderDel);
        } else if (schoolBureauLevel == 2) {
            TermQueryBuilder builderDel = new TermQueryBuilder("provinceCode", districtCode);
            boolQueryBuilder.must(builderDel);
        }
        boolQueryBuilder.must(builderType);
        // 1.将学段名称转换成代码
        YxyResPhase yxyResPhase = yxyResPhaseRepository.findByName(xueduan);
        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        if (yxyResPhase != null && !yxyResPhase.getId().equals("")) {
            // 2.根据学段id查询记录
            TermQueryBuilder builderType2 = new TermQueryBuilder("stage", yxyResPhase.getId());
            boolQueryBuilder.must(builderType2);
            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("weikeSubject").size(100);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);
            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                long value = gradeBucket.getDocCount();
                map.put(key, value);

                System.out.println(key + "科目有" + value + "个资源。");
                System.out.println();
            }
        }
        return map;
    }

    @Override
    public Map<String, Object> statisticsResourcePhaseCount2(String xueduan, String districtCode, Integer schoolBureauLevel) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderTypee = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderTypee);
        if (schoolBureauLevel == 0) {
            TermQueryBuilder builderDel = new TermQueryBuilder("districtCode", districtCode);
            boolQueryBuilder.must(builderDel);
        } else if (schoolBureauLevel == 1) {
            TermQueryBuilder builderDel = new TermQueryBuilder("cityCode", districtCode);
            boolQueryBuilder.must(builderDel);
        } else if (schoolBureauLevel == 2) {
            TermQueryBuilder builderDel = new TermQueryBuilder("provinceCode", districtCode);
            boolQueryBuilder.must(builderDel);
        }
        boolQueryBuilder.mustNot(builderType);
        // 1.将学段名称转换成代码
        YxyResPhase yxyResPhase = yxyResPhaseRepository.findByName(xueduan);
        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        if (yxyResPhase != null && !yxyResPhase.getId().equals("")) {
            // 2.根据学段id查询记录
            TermQueryBuilder builderType2 = new TermQueryBuilder("phaseIdList", yxyResPhase.getId());
            boolQueryBuilder.must(builderType2);

            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("subjectIdList").size(100);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);

            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();

            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                long value = gradeBucket.getDocCount();
                map.put(key, value);

                System.out.println(key + "科目有" + value + "个资源。");
                System.out.println();
            }
        }
        return map;
    }

    /**
     * 资源统计学校的资源统计的统计分析 资源部分
     */
    @Override
    public Map<String, Object> statisticsSchoolResourceTypeCount(String school, String xueduan) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderTypeSchool = new TermQueryBuilder("uploaderSchoolId", school);
        boolQueryBuilder.mustNot(builderType);
        boolQueryBuilder.must(builderTypeSchool);

        TermQueryBuilder builderTypee = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderTypee);
        // 1.将学段名称转换成代码
        YxyResPhase yxyResPhase = yxyResPhaseRepository.findByName(xueduan);
        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        if (yxyResPhase != null && !yxyResPhase.getId().equals("")) {
            // 2.根据学段id查询记录
            TermQueryBuilder builderType2 = new TermQueryBuilder("phaseIdList", yxyResPhase.getId());
            boolQueryBuilder.must(builderType2);
            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("subjectIdList").size(100);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);
            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                long value = gradeBucket.getDocCount();
                map.put(key, value);

                System.out.println(key + "科目有" + value + "个资源。");
                System.out.println();
            }
        }
        return map;
    }

    /**
     * 资源统计学校的资源统计的统计分析 微课部分
     */
    @Override
    public Map<String, Object> statisticsSchoolWeikeTypeCount(String school, String xueduan) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");

        TermQueryBuilder builderTypeSchool = new TermQueryBuilder("uploaderSchoolId", school);
        boolQueryBuilder.must(builderType);
        boolQueryBuilder.must(builderTypeSchool);

        TermQueryBuilder builderTypee = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderTypee);
        // 1.将学段名称转换成代码
        YxyResPhase yxyResPhase = yxyResPhaseRepository.findByName(xueduan);
        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        if (yxyResPhase != null && !yxyResPhase.getId().equals("")) {
            // 2.根据学段id查询记录
            TermQueryBuilder builderType2 = new TermQueryBuilder("stage", yxyResPhase.getId());
            boolQueryBuilder.must(builderType2);
            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("weikeSubject").size(100);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);
            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                long value = gradeBucket.getDocCount();
                map.put(key, value);

                System.out.println(key + "科目有" + value + "个资源。");
                System.out.println();
            }
        }
        return map;
    }

    // 教育局平台办公 资源统计 饼形图 资源学科分布
    @Override
    public Map<String, Long> resourcePhaseCount(String stageName, String districtCode, Integer schoolBureauLevel) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        TermQueryBuilder builderTypee = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderTypee);
        TermQueryBuilder builderDel = null;
        if (schoolBureauLevel == 0) {
            builderDel = new TermQueryBuilder("districtCode", districtCode);
        } else if (schoolBureauLevel == 1) {
            builderDel = new TermQueryBuilder("cityCode", districtCode);
        } else if (schoolBureauLevel == 2) {
            builderDel = new TermQueryBuilder("provinceCode", districtCode);
        }
        boolQueryBuilder.must(builderDel);
        // 1.将学段名称转换成代码
        YxyResPhase yxyResPhase = yxyResPhaseRepository.findByName(stageName);

        // 返回
        Map<String, Long> map = new HashMap<String, Long>();
        if (yxyResPhase != null && !yxyResPhase.getId().equals("")) {
            BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
            TermQueryBuilder builderType2 = new TermQueryBuilder("phaseIdList", yxyResPhase.getId());
            TermQueryBuilder builderType3 = new TermQueryBuilder("stage", yxyResPhase.getId());
            knoBuilder.should(builderType2);
            knoBuilder.should(builderType3);
            boolQueryBuilder.must(knoBuilder);

            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);

            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("subjectIdList").size(100);
            TermsBuilder gradeTermsBuilder2 = AggregationBuilders.terms("stage").field("weikeSubject").size(100);

            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).addAggregation(gradeTermsBuilder).addAggregation(gradeTermsBuilder2).execute().actionGet();

            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                System.out.println("key:" + key);
                long value = gradeBucket.getDocCount();
                map.put(key, value);
                System.out.println(key + "科目有" + value + "个资源。");
                System.out.println();
            }

            StringTerms gradeTerms1 = (StringTerms) aggMap.get("stage");
            Iterator<Bucket> gradeBucketIt1 = gradeTerms1.getBuckets().iterator();
            while (gradeBucketIt1.hasNext()) {
                Bucket gradeBucket = gradeBucketIt1.next();
                String key = (String) gradeBucket.getKey();
                System.out.println("key:" + key);
                long value = gradeBucket.getDocCount();
                map.put(key, map.get(key) != null ? map.get(key) + value : value);
                System.out.println(key + "科目有" + value + "个微克。");
                System.out.println();
            }
        }
        return map;

    }

    // 备课包学科分布
    @Autowired
    private YxyLecturePrePackRepository yxyLecturePrePackRepository;

    @Override
    public List<Long> packSubjectCount(String phaseName, String districtCode, Integer schoolBureauLevel) {

        YxyResPhase yxyResPhase = yxyResPhaseRepository.findByName(phaseName);

        long yuwenCount = 0l;
        Long shuxueCount = 0l;
        Long yingyuCount = 0l;
        Long sixiangCount = 0l;
        Long wuliCount = 0l;
        Long huaxueCount = 0l;
        Long lishiCount = 0l;
        Long shengwuCount = 0l;
        Long diliCount = 0l;

        // 语文jcsub01,数学jcsub02,英语jcsub03,思想政治jcsub09,物理jcsub13,化学jcsub14,历史jcsub11,生物jcsub15,地理jcsub12
        if (schoolBureauLevel == 0) {

            yuwenCount = yxyLecturePrePackRepository.countByAreaIdDistrictAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub01");
            shuxueCount = yxyLecturePrePackRepository.countByAreaIdDistrictAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub02");
            yingyuCount = yxyLecturePrePackRepository.countByAreaIdDistrictAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub03");
            sixiangCount = yxyLecturePrePackRepository.countByAreaIdDistrictAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub09");
            wuliCount = yxyLecturePrePackRepository.countByAreaIdDistrictAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub13");
            huaxueCount = yxyLecturePrePackRepository.countByAreaIdDistrictAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub14");
            lishiCount = yxyLecturePrePackRepository.countByAreaIdDistrictAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub11");
            shengwuCount = yxyLecturePrePackRepository.countByAreaIdDistrictAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub15");
            diliCount = yxyLecturePrePackRepository.countByAreaIdDistrictAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub12");
        } else if (schoolBureauLevel == 1) {

            yuwenCount = yxyLecturePrePackRepository.countByAreaIdCityAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub01");
            shuxueCount = yxyLecturePrePackRepository.countByAreaIdCityAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub02");
            yingyuCount = yxyLecturePrePackRepository.countByAreaIdCityAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub03");
            sixiangCount = yxyLecturePrePackRepository.countByAreaIdCityAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub09");
            wuliCount = yxyLecturePrePackRepository.countByAreaIdCityAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub13");
            huaxueCount = yxyLecturePrePackRepository.countByAreaIdCityAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub14");
            lishiCount = yxyLecturePrePackRepository.countByAreaIdCityAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub11");
            shengwuCount = yxyLecturePrePackRepository.countByAreaIdCityAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub15");
            diliCount = yxyLecturePrePackRepository.countByAreaIdCityAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub12");

        } else if (schoolBureauLevel == 2) {

            yuwenCount = yxyLecturePrePackRepository.countByAreaIdProvinceAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub01");
            shuxueCount = yxyLecturePrePackRepository.countByAreaIdProvinceAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub02");
            yingyuCount = yxyLecturePrePackRepository.countByAreaIdProvinceAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub03");
            sixiangCount = yxyLecturePrePackRepository.countByAreaIdProvinceAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub09");
            wuliCount = yxyLecturePrePackRepository.countByAreaIdProvinceAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub13");
            huaxueCount = yxyLecturePrePackRepository.countByAreaIdProvinceAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub14");
            lishiCount = yxyLecturePrePackRepository.countByAreaIdProvinceAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub11");
            shengwuCount = yxyLecturePrePackRepository.countByAreaIdProvinceAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub15");
            diliCount = yxyLecturePrePackRepository.countByAreaIdProvinceAndPhaseIdAndSubjectId(districtCode, yxyResPhase.getId(), "jcsub12");

        }
        List<Long> packCountLst = new ArrayList<Long>();
        packCountLst.add(yuwenCount);
        packCountLst.add(shuxueCount);
        packCountLst.add(yingyuCount);
        packCountLst.add(sixiangCount);
        packCountLst.add(wuliCount);
        packCountLst.add(huaxueCount);
        packCountLst.add(lishiCount);
        packCountLst.add(shengwuCount);
        packCountLst.add(diliCount);
        return packCountLst;

    }
}
